package com.ctvit.framework.util;

import org.apache.log4j.Logger;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author wks
 * @date 2022/4/1 17:40
 */

public class HttpUtils {

    private static final Logger LOGGER = Logger.getLogger(HttpUtils.class);

    public static String JsonHttpRequestPost(String requestUrl, String requestMethod, JSONObject outputStr, Integer tryNum) throws IOException {
        StringBuffer rstsb = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置发送数据
            conn.setDoOutput(true);
            //设置接受数据
            conn.setDoInput(true);
            //设置请求的方法类型
            conn.setRequestMethod(requestMethod);
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            //设置请求的内容类型
            conn.setRequestProperty("Content-Type", "application/json");
            conn.connect();

            //往服务器端写内容 也就是发起http请求需要带的参数
            if (outputStr != null) {
                //发送数据,使用输出流
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.toString().getBytes("UTF-8"));
                os.close();
            }

            //读取服务器端返回的内容,获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                rstsb.append(line);
                rstsb.append("\n");
            }
            br.close();

            //断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();

        } catch (Exception e) {
            if (tryNum.equals(0)) {
                return null;
            }
            Integer haveNum = tryNum - 1;
            LOGGER.error("当前剩余执行重试次数:" + haveNum + "");
            JsonHttpRequestPost(requestUrl, requestMethod, outputStr, haveNum);
            e.printStackTrace();
        }

        return rstsb.toString();
    }

    public static void main(String[] args) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("zChanlCd", "0012");
        JsonHttpRequestPost("http://127.0.0.1:9090/oms/extension/cdmChannel/v1/saveChannel", "POST", jsonObject, 3);
    }


}
